#-*- coding:utf-8 -*-
import accomm
import wx
import sys

(UpdateViewEvent, EVT_UPDATE_VIEW) = wx.lib.newevent.NewEvent()

class ComlogPanel(wx.Panel):
    def __init__(self, parent, serial):
        wx.Panel.__init__(self, parent, -1)
        
        self.comlog = Comlog(serial)
        self.comlog.setView(self)

        # 화면 구성
        list = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        list.InsertColumn(0, "Src")
        list.InsertColumn(1, "Dest")
        list.InsertColumn(2, "Mode")
        list.InsertColumn(3, "Data")
        
        list.SetColumnWidth(0, 40)
        list.SetColumnWidth(1, 40)
        list.SetColumnWidth(2, 40)
        list.SetColumnWidth(3, 300)

        filterStr = wx.StaticText(self, -1, "Filter :")
        filterText = wx.TextCtrl(self, -1, style = wx.TE_READONLY)
        filterText.Enable(False)
        filterBtn = wx.Button(self, -1, "Change")
        #filterBtn.SetSize(filterBtn.GetBestSize())
        
        fsizer = wx.BoxSizer(wx.HORIZONTAL)
        fsizer.Add(filterStr, 0, wx.ALL, 5)
        fsizer.Add(filterText, 1, wx.ALL, 2)
        fsizer.Add(filterBtn, 0, wx.EXPAND)
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(fsizer, 0, wx.EXPAND)
        sizer.Add(list, 1, wx.EXPAND)
        self.SetSizer(sizer)
        #self.SetAutoLayout(True)
                
        self.list = list
        
        # Link event
        self.Bind(EVT_UPDATE_VIEW, self.OnUpdate)

    def start(self):
        self.comlog.start()
        
    def stop(self):
        self.comlog.stop()
        
    def OnUpdate(self, evt):
        index = self.list.InsertStringItem(sys.maxint, '%02X' % evt.src)
        self.list.SetStringItem(index, 1, '%02X' % evt.dest)
        self.list.SetStringItem(index, 2, '%02X' % evt.mode)
        
        str = ''
        for data in evt.data:
            str = str + '%02X ' % data
            
        self.list.SetStringItem(index, 3, str)
#        print 'Event : Update'
        


        
class Comlog(object):
    def __init__(self, serial):
        self._serial = serial
        self._linker = accomm.Linker()
        self._linker.addListener(self.receiveFunc)
        self._buf = []
        self._view = None
    
    def start(self):
        self._linker.connect(self._serial)
    
    def stop(self):
        self._linker.disconnect()
        
    def receiveFunc(self, data):
        self._buf.append(data)
        
        src = data[0]
        dest = data[1]
        mode = data[2]
        data = data[3:]

        if self._view:
            evt = UpdateViewEvent(src = src, dest = dest, mode = mode, data = data)
            wx.PostEvent(self._view, evt)
        
    
    def setView(self,view):
        self._view = view
    
        
    
    
    
    